<template>
  <base-breadcrumb :breadcrumb="!isAudit">
    <a-card>
      <titleName title="基本信息" />
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
        :wrapper-col="{ lg: { span: 16 }, sm: { span: 16 } }"
      >
        <a-row :gutter="24">
          <a-col
            :md="16"
            :sm="16"
          >
            <a-form-model-item
              label="所属单位"
              prop="projectId"
            >
              <org-tree-select
                v-model="form.projectId"
                is-auto-select-first
                :is-query-projec-detail="false"
                is-need-auth
                check-strictly
                disabled
                @select="selectOrg"
              />
            </a-form-model-item>
          </a-col>
          <!--          <a-col-->
          <!--            :md="8"-->
          <!--            :sm="8"-->
          <!--          >-->
          <!--            <a-form-model-item-->
          <!--              label="所属分公司"-->
          <!--              prop="branchComId"-->
          <!--            >-->
          <!--              <SelectSubCompany-->
          <!--                v-model="form.branchComId"-->
          <!--                placeholder="请选择"-->
          <!--                :disabled="pageType == 'look'"-->
          <!--              />-->
          <!--            </a-form-model-item>-->
          <!--          </a-col>-->
          <!--          <a-col-->
          <!--            :md="8"-->
          <!--            :sm="8"-->
          <!--          >-->
          <!--            <a-form-model-item-->
          <!--              label="所属项目"-->
          <!--              prop="projectId"-->
          <!--            >-->
          <!--              <SelectProject-->
          <!--                v-model="form.projectId"-->
          <!--                placeholder="请选择"-->
          <!--                :form="form"-->
          <!--                :is-clear="id == ''"-->
          <!--                key-value="branchComId"-->
          <!--                :disabled="pageType == 'look'"-->
          <!--                @change="handleChange"-->
          <!--              />-->
          <!--            </a-form-model-item>-->
          <!--          </a-col>-->
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="建筑面积（地上/地下）(㎡)"
              prop="constructionArea"
            >
              <a-input
                v-model="form.constructionArea"
                :disabled="pageType == 'look'"
                placeholder="请输入"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="建筑物高度/层高/层数（地上/地下)"
              prop="buildingHeight"
            >
              <BaseInput
                v-model="form.buildingHeight"
                :disabled="pageType == 'look'"
                placeholder="请输入"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="承包范围"
              prop="contractScope"
            >
              <BaseInput
                v-model="form.contractScope"
                :disabled="pageType == 'look'"
                placeholder="请输入"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="结算方式"
              prop="settleMethod"
            >
              <BaseInput
                v-model="form.settleMethod"
                :disabled="pageType == 'look'"
                placeholder="请输入"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="结构形式"
              prop="structureTypeName"
            >
              <BaseInput
                v-model="form.structureTypeName"
                disabled
                placeholder="请输入"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="开工日期"
              prop="contractStartDate"
            >
              <BaseInput
                v-model="form.contractStartDate"
                disabled
                placeholder="请输入"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="竣工日期"
              prop="contractEndDate"
            >
              <BaseInput
                v-model="form.contractEndDate"
                disabled
                placeholder="请输入"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="合同范围内精装饰内容"
              prop="contractDecoration"
            >
              <BaseInput
                v-model="form.contractDecoration"
                :disabled="pageType == 'look'"
                placeholder="请输入"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
          <a-form-model-item label="还原与总结完成时间:" prop="finishDate">
                <a-date-picker  :disabled="pageType == 'look'" v-model="form.finishDate" @change="(date, dateString) => getTime(date, dateString, 'form', 'finishDate')" />
                <!-- <a-input  v-model="form.informantTime" :disabled="pageType == 'looks'" /> -->
              </a-form-model-item>
          </a-col>
          <a-col
            :md="24"
            :sm="24"
            class="title mt20"
          >
            合同造价（万元）
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="不含税："
              prop="amountExTax"
            >
              <a-input-number
                v-model="form.amountExTax"
                :max="99999999999999"
                :disabled="pageType == 'look'"
                :min="0"
                placeholder="请输入"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item
              label="增值税："
              prop="tax"
            >
              <a-input-number
                v-model="form.tax"
                :max="99999999999999"
                :disabled="pageType == 'look'"
                :min="0"
                placeholder="请输入"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="8"
            :sm="8"
          >
            <a-form-model-item label="含税：">
              <a-input-number
                :max="99999999999999"
                disabled
                placeholder="请输入"
                :precision="2"
                :value="form.amountExTax + form.tax > 0 ? form.amountExTax + form.tax : 0"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            v-if="pageType != 'look'"
            :md="24"
            :sm="24"
          >
            <a-form-model-item label="附件上传">
              <upload-list
                :business-code="'BM23'"
                :upload-arrys.sync="form.fileInfoVOList"
                multiple
                @fileArrysData="handleFileUploaded"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            v-else
            :md="24"
            :sm="24"
          >
            <a-form-model-item label="附件">
              <file-link :file-list="form.fileInfoVOList" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>
    <a-card>
      <titleName title="数据填写" />

      <div class="flex mt20 mb20">
        <div
          :md="24"
          :sm="24"
          class="title mt20"
        >
          成本还原：
        </div>
        <a-button
          v-if="pageType != 'look'"
          type="primary"
          @click="handleItem('add', {}, 'tabe1')"
        >
          新增行
        </a-button>
      </div>
      <s-table
        ref="table1"
        class="updateCostReduction-table"
        size="default"
        row-key="key"
        :columns="pageType == 'look' ? columnsLook1 : columns1"
        :data="loadData1"
        :alert="true"
        show-size-changer
        :default-expanded-row-keys="expandedRowKeys"
        :expanded-row-keys="expandedRowKeys"
        show-quick-jumper
        :show-pagination="false"
        @expand="expandedRowsChange"
      >
        <div
          v-for="col in ['amountWithoutTax', 'amountOfPerMeter']"
          :slot="col"
          :key="col"
          slot-scope="text, record, index"
        >
          <template v-if="index === form.costReductionServiceList.length - 1 && !record.isChildren">
            {{
              text ? text.toFixed(2) : '0.00'
            }}
          </template>
          <a-input-number
            v-else
            :max="99999999999999"
            :value="text"
            style="border-color: #e4ac0b; background-color: #fff9e8; margin: -5px 0; width: 100%"
            :disabled="pageType == 'look'"
            :min="0"
            :precision="2"
            placeholder="请输入"
            @blur="onBlur"
            @change="(e) => handleInput(e, record.key, col)"
          />
        </div>
        <template
          slot="sortNum"
          slot-scope="text, record, index"
        >
          <span v-if="index === form.costReductionServiceList.length - 1 && !record.isChildren" />
          <a-input
            v-else
            v-model="record.sortNum"
            style="border-color: #e4ac0b; background-color: #fff9e8; margin: -5px 0; width: 70%"
            :disabled="pageType == 'look'"
          />
        </template>
        <span
          slot="name"
          slot-scope="text, record, index"
          class="requiredFormItem"
        >
          <span v-if="index === form.costReductionServiceList.length - 1 && !record.isChildren">合计</span>
          <a-input
            v-else
            v-model="record.name"
            :disabled="pageType == 'look'"
          />
        </span>

        <span
          slot="action"
          slot-scope="text, record, index"
        >
          <span v-if="index === form.costReductionServiceList.length - 1 && !record.isChildren" />
          <div v-else>
            <a
              v-if="!record.isChildren"
              :disabled="pageType == 'look'"
              @click="handleItem('addchild', record, 'tabe1')"
            >添加子项</a>
            <a-divider
              v-if="!record.isChildren"
              type="vertical"
            />
            <a
              :disabled="pageType == 'look'"
              @click="handleItem('del', record, 'tabe1')"
            >移除</a>
          </div>
        </span>
      </s-table>

      <div class="flex mt20 mb20">
        <div
          :md="24"
          :sm="24"
          class="title mt20"
        >
          指标分析：
        </div>
        <a-button
          v-if="pageType != 'look'"
          type="primary"
          @click="handleItem('add', {}, 'tabe2')"
        >
          新增行
        </a-button>
      </div>
      <s-table
        ref="table2"
        size="default"
        class="updateCostReduction-table"
        row-key="key"
        :columns="pageType == 'look' ? columnsLook2 : columns2"
        :data="loadData2"
        :alert="true"
        show-size-changer
        show-quick-jumper
        :show-pagination="false"
      >
        <span
          slot="serial"
          slot-scope="text, record, index"
        >{{ index + 1 }}</span>
        <div v-for="col in ['value', 'onTheGround', 'underground']"
        :slot="col"
        slot-scope="text, record" :key="col">
          <a-input-number
            :max="99999999999999"
            style="border-color: #e4ac0b; background-color: #fff9e8; margin: -5px 0; width: 100%"
            :value="text"
            :min="0"
            :precision="2"
            :disabled="pageType == 'look'"
            placeholder="请输入"
            @change="(e) => handleInput2(e, record.key, col)"
          />
        </div>
        <span
          slot="name"
          slot-scope="text, record"
          class="requiredFormItem"
        >
          <a-input
            v-model="record.name"
            placeholder="请输入"
            :disabled="pageType == 'look'"
          />
        </span>
        <span
          slot="action"
          slot-scope="text, record"
        >
          <a
            :disabled="pageType == 'look'"
            @click="handleItem('del', record, 'tabe2')"
          >移除</a>
        </span>
      </s-table>

      <div class="flex mt20 mb20">
        <div
          :md="24"
          :sm="24"
          class="title mt20"
        >
          施工做法：
        </div>
        <a-button
          v-if="pageType != 'look'"
          type="primary"
          @click="handleItem('add', {}, 'tabe3')"
        >
          新增行
        </a-button>
      </div>
      <s-table
        ref="table3"
        size="default"
        row-key="key"
        class="updateCostReduction-table"
        :columns="pageType == 'look' ? columnsLook3 : columns3"
        :data="loadData3"
        :alert="true"
        show-size-changer
        show-quick-jumper
        :show-pagination="false"
      >
        <span
          slot="serial"
          slot-scope="text, record, index"
        >{{ index + 1 }}</span>

        <span
          slot="content"
          slot-scope="text, record"
          class="requiredFormItem"
        >
          <a-input
            v-model="record.content"
            :disabled="pageType == 'look'"
          />
        </span>
        <span
          slot="name"
          slot-scope="text, record"
          class="requiredFormItem"
        >
          <a-input
            v-model="record.name"
            :disabled="pageType == 'look'"
          />
        </span>

        <span
          slot="action"
          slot-scope="text, record"
        >
          <a
            :disabled="pageType == 'look'"
            @click="handleItem('del', record, 'tabe3')"
          >移除</a>
        </span>
      </s-table>
    </a-card>
    <div
      v-if="pageType != 'look'"
      class="tool-btns page-btn-right-top"
    >
      <!-- <a-button
        v-if="id != '' && form.auditStatus == 'DRAFT'"
        type="danger"
        :loading="loading.DELETE"
        @click="handleSave('DELETE')"
      >
        删除草稿
      </a-button> -->
      <!-- <a-button
        v-if="form.auditStatus == 'REJECTED'"
        type="primary"
        :loading="loading.REJECTED"
        @click="handleSave('REJECTED')"
      >
        保存
      </a-button> -->
      <a-button
        type="primary"
        :disabled="!isSubmit"
        :loading="loading.DRAFT"
        @click="handleSave('DRAFT')"
      >
        保存草稿
      </a-button>
      <a-button
        type="primary"
        :disabled="!isSubmit"
        :loading="loading.SUBMITTED"
        @click="handleSave('SUBMITTED')"
      >
        提交
      </a-button>
      <a-button
        type="primary"
        @click="handleClose"
      >
        关闭
      </a-button>
    </div>
    <div
      v-else
      class="tool-btns page-btn-right-top"
    >
      <a-button
        v-if="checkVisibleInDetail"
        type="primary"
        @click="handleClose"
      >
        关闭
      </a-button>
    </div>
    <selectApprover
      :business-id="businessId"
      :process-config="setProcessConfig"
    />
  </base-breadcrumb>
</template>
<script>
import { getProjectInfo } from '@/api/businessAffairs/revenueAndCost'
import {
    getCostReduction,
    addCostReduction,
    editCostReduction,
    delCostReduction,
    checkCostReduction
} from '@/api/businessAffairs/revenueAndCost'
import { getSelectListByType, getSelectListTreeByTypeList } from '@/api/businessAffairs/common.js'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import { isAttachment, checkVisibleInDetail } from '@/utils/util'
import { STable } from '@/components'
import UploadList from '@/components/UploadList'
const columns1 = [
    {
        title: '序号',
        dataIndex: 'sortNum',
        width: '15%',
        custom: true,
        scopedSlots: { customRender: 'sortNum' }
    },

    {
        title: '名称',
        dataIndex: 'name',
        scopedSlots: { customRender: 'name' }
    },
    {
        title: '（不含税）金额（元）',
        dataIndex: 'amountWithoutTax',
        scopedSlots: { customRender: 'amountWithoutTax' }
    },
    {
        title: '平米指标（元／㎡）',
        dataIndex: 'amountOfPerMeter',
        scopedSlots: { customRender: 'amountOfPerMeter' }
    },
    {
        title: '操作',
        dataIndex: 'action',
        width: '170px',
        scopedSlots: { customRender: 'action' }
    }
]

const columnsLook1 = [
    {
        title: '序号',
        dataIndex: 'sortNum',
        width: '15%',
        custom: true,
        scopedSlots: { customRender: 'sortNum' }
    },

    {
        title: '名称',
        dataIndex: 'name',
        scopedSlots: { customRender: 'name' }
    },
    {
        title: '（不含税）金额（元）',
        dataIndex: 'amountWithoutTax',
        scopedSlots: { customRender: 'amountWithoutTax' }
    },
    {
        title: '平米指标（元／㎡）',
        dataIndex: 'amountOfPerMeter',
        scopedSlots: { customRender: 'amountOfPerMeter' }
    }
]
const columns2 = [
    {
        title: '名称',
        dataIndex: 'name',
        scopedSlots: { customRender: 'name' }
    },
    {
        title: '值',
        dataIndex: 'value',
        scopedSlots: { customRender: 'value' }
    },
    {
        title: '其中：地上',
        dataIndex: 'onTheGround',
        scopedSlots: { customRender: 'onTheGround' }
    },
    {
        title: '地下',
        dataIndex: 'underground',
        scopedSlots: { customRender: 'underground' }
    },

    {
        title: '操作',
        dataIndex: 'action',
        width: '170px',
        scopedSlots: { customRender: 'action' }
    }
]
const columnsLook2 = [
    {
        title: '名称',
        dataIndex: 'name',
        scopedSlots: { customRender: 'name' }
    },
    {
        title: '值',
        dataIndex: 'value',
        scopedSlots: { customRender: 'value' }
    },
    {
        title: '其中：地上',
        dataIndex: 'onTheGround',
        scopedSlots: { customRender: 'onTheGround' }
    },
    {
        title: '地下',
        dataIndex: 'underground',
        scopedSlots: { customRender: 'underground' }
    }
]
const columns3 = [
    {
        title: '名称',
        dataIndex: 'name',
        scopedSlots: { customRender: 'name' }
    },
    {
        title: '内容',
        dataIndex: 'content',
        scopedSlots: { customRender: 'content' }
    },

    {
        title: '操作',
        dataIndex: 'action',
        width: '170px',
        scopedSlots: { customRender: 'action' }
    }
]
const columnsLook3 = [
    {
        title: '名称',
        dataIndex: 'name',
        scopedSlots: { customRender: 'name' }
    },
    {
        title: '内容',
        dataIndex: 'content',
        scopedSlots: { customRender: 'content' }
    }
]
export default {
    name: 'a' + Date.now(),
    components: {
        SelectSubCompany,
        SelectProject,
        STable,
        UploadList
    },
    data() {
        this.columns1 = columns1
        this.columns2 = columns2
        this.columns3 = columns3
        this.columnsLook1 = columnsLook1
        this.columnsLook2 = columnsLook2
        this.columnsLook3 = columnsLook3
        return {
            checkVisibleInDetail: checkVisibleInDetail(this),
            loading: {
                DELETE: false,
                DRAFT: false,
                SUBMITTED: false,
                REJECTED: false
            },
            form: {
                structureTypeName: '',
                contractStartDate: '',
                fileInfoVOList: [],
                indicatorAnaysisServiceList: [],
                constructionPracticesServiceList: [],
                costReductionServiceList: [],
                finishDate:''
            },
            key1: 0,
            key2: 0,
            key3: 0,
            expandedRowKeys: [],
            rules: {
                branchComId: [{ required: true, message: '请选择分公司' }],
                projectId: [{ required: true, message: '请选择项目' }],
                constructionArea: [{ required: true, message: '请输入' }],
                buildingHeight: [{ required: true, message: '请输入' }],
                contractScope: [{ required: true, message: '请输入' }],
                settleMethod: [{ required: true, message: '请输入' }],
                contractDecoration: [{ required: true, message: '请输入' }],
                amountExTax: [{ required: true, message: '请输入' }],
                tax: [{ required: true, message: '请输入' }],
                finishDate: [{required: true, message: '请选择',change:true}]
            },
            id: '',
            isSubmit: true,
            pageType: '',
            loadData1: () => {
                return new Promise((resolve, reject) => {
                    resolve({
                        data: this.form.costReductionServiceList
                    })
                })
            },
            loadData2: () => {
                return new Promise((resolve, reject) => {
                    resolve({
                        data: this.form.indicatorAnaysisServiceList
                    })
                })
            },
            loadData3: () => {
                return new Promise((resolve, reject) => {
                    resolve({
                        data: this.form.constructionPracticesServiceList
                    })
                })
            },
            //获取流程配置值
            processConfig: null,
            //点击提交发送流程配置值
            setProcessConfig: null,
            businessId: null
        }
    },
    props: {
        isAudit: {
            // 是否作为审批详情
            type: Boolean,
            default: false
        }
    },
    watch: {
        isAudit: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.$nextTick(() => {
                        this.pageType = 'look'
                    })
                }
            }
        }
    },
    async mounted() {
        if (this.$route.query.id) {
            this.id = this.$route.query.id
            console.log(this.id)
            this.checkCostReductionReq()
        }
        this.pageType = this.$route.query.pageType
        if (this.pageType == 'look') {
            this.$route.meta.title = '成本还原、总结查看'
            // this.columns1 = columnsLook1
            // this.columns2 = columnsLook2
            // this.columns3 = columnsLook3
        } else {
            this.$route.meta.title = this.id == '' ? '成本还原、总结新增' : '成本还原、总结编辑'
        }
        if (this.pageType == 'add') {
            this.getSelectListByTypeReq(13)
            this.getSelectListByTypeReq(11)
            this.getSelectTreeListByTypeReq(12)
        }
        //获取通过获取流程配置值
       this.processConfig = await this.$getConfigFn('comm_cost_reduction_return_conclusion')
    },

    methods: {
        selectOrg(val) {
          if(val&&val.length) {
            this.form.branchComId = val[val.length - 2].orgId
            this.handleChange(this.form.projectId)
          }
        },
        expandedRowsChange(expanded, record) {
            console.log(expanded)
            console.log(record)
            if (expanded) {
                this.expandedRowKeys = [record.key]
            } else {
                this.expandedRowKeys = []
            }
        },
        handleFileUploaded(list) {
            this.form.fileInfoVOList = [...list]
        },
        async getSelectTreeListByTypeReq(type) {
            const [err, res] = await getSelectListTreeByTypeList({ type: type, isParent: true })
            if (!err) {
                res.data.forEach((item) => {
                    item.children.forEach((i) => {
                        i.key = i.id
                        i.amountWithoutTax = 0
                        i.amountOfPerMeter = 0
                        i.isChildren = true
                        delete i.children
                    })
                    item.key = item.id
                    item.amountWithoutTax = 0
                    item.amountOfPerMeter = 0
                })
                this.form.costReductionServiceList = res.data
                console.log(this.form.costReductionServiceList)
                this.getCombined()
                this.$refs.table1.refresh(true)
            }
        },
        async getSelectListByTypeReq(type) {
            const [err, res] = await getSelectListByType({ type: type })
            if (!err) {
                if (type == 13) {
                    res.data.forEach((item, index) => {
                        this.form.indicatorAnaysisServiceList.push({
                            name: item.name,
                            onTheGround: 0,
                            underground: 0,
                            value: 0,
                            key: this.key2
                        })
                        this.key2++
                    })
                    this.$refs.table2.refresh(true)
                } else {
                    res.data.forEach((item, index) => {
                        this.form.constructionPracticesServiceList.push({
                            content: '',
                            name: item.name,
                            key: this.key3
                        })
                        this.key3++
                    })
                    this.$refs.table3.refresh(true)
                }
            }
        },
        getCombined() {
            // this.form.itemList.pop()
            this.key1++
            this.form.costReductionServiceList.push({
                name: '合计',
                amountOfPerMeter: this.sum(this.form.costReductionServiceList, 'amountOfPerMeter'),
                amountWithoutTax: this.sum(this.form.costReductionServiceList, 'amountWithoutTax'),
                key: this.key1
            })

            this.$refs.table1.refresh(true)
        },
        sum(arr, str) {
            let sum = 0
            for (let i = 0; i < arr.length; i++) {
                sum += arr[i][str]
            }
            return sum
        },
        handleInput(value, key, column) {
            const newData = [...this.form.costReductionServiceList]
            console.log(key)
            const target = newData.filter((item) => key === item.key)[0]

            if (target) {
                target[column] = value
            } else {
                console.log(newData)
                newData.forEach((item) => {
                    if (item.children) {
                        item.children.forEach((i) => {
                            if (i.key == key) {
                                i[column] = value
                            }
                        })
                    }
                })
            }
            this.form.costReductionServiceList = newData
        },
        onBlur() {
            this.form.costReductionServiceList.pop()
            this.getCombined()
        },
        handleInput2(value, key, column) {
            const newData = [...this.form.indicatorAnaysisServiceList]
            const target = newData.filter((item) => key === item.key)[0]
            if (target) {
                target[column] = value
                this.form.indicatorAnaysisServiceList = newData
            }
        },
        handleInput3(value, key, column) {
            const newData = [...this.form.constructionPracticesServiceList]
            const target = newData.filter((item) => key === item.key)[0]
            if (target) {
                target[column] = value
                this.form.constructionPracticesServiceList = newData
            }
        },

        handleItem(type, data, tabeType) {
            if (tabeType == 'tabe1') {
                console.log(this.expandedRowKeys)

                if (type == 'add') {
                    this.form.costReductionServiceList.splice(this.form.costReductionServiceList.length - 1, 0, {
                        name: '',
                        sortNum: '',
                        parentId: 'null',
                        amountOfPerMeter: 0,
                        amountWithoutTax: 0,
                        children: [],

                        key: new Date().getTime()
                    })
                } else if (type == 'addchild') {
                    this.expandedRowKeys = [data.key]
                    data.children.push({
                        name: '',
                        sortNum: '',
                        isChildren: true,
                        amountOfPerMeter: 0,
                        amountWithoutTax: 0,
                        parentId: this.key1,
                        key: new Date().getTime()
                    })
                } else {
                    this.form.costReductionServiceList.forEach((item, index) => {
                        if (item.key == data.key) {
                            this.form.costReductionServiceList.splice(index, 1)
                        }
                        if (item.children) {
                            item.children.forEach((e, i) => {
                                if (e.key == data.key) {
                                    item.children.splice(i, 1)
                                }
                            })
                        }
                    })
                }
                this.form.costReductionServiceList.pop()
                this.getCombined()
            } else if (tabeType == 'tabe2') {
                if (type == 'add') {
                    this.key2++
                    this.form.indicatorAnaysisServiceList.splice(this.form.indicatorAnaysisServiceList.length, 0, {
                        name: '',

                        onTheGround: 0,
                        underground: 0,
                        value: 0,
                        key: this.key2
                    })
                } else {
                    this.form.indicatorAnaysisServiceList.forEach((item, index) => {
                        if (item.key == data.key) {
                            this.form.indicatorAnaysisServiceList.splice(index, 1)
                        }
                    })
                }
                this.$refs.table2.refresh(true)
            } else {
                if (type == 'add') {
                    this.key3++
                    this.form.constructionPracticesServiceList.splice(
                        this.form.constructionPracticesServiceList.length,
                        0,
                        {
                            content: '',
                            name: '',
                            key: this.key3
                        }
                    )
                } else {
                    this.form.constructionPracticesServiceList.forEach((item, index) => {
                        if (item.key == data.key) {
                            this.form.constructionPracticesServiceList.splice(index, 1)
                        }
                    })
                }
                this.$refs.table3.refresh(true)
            }
        },
        getTime(date, dateString, type, name) {
            this[type][name] = dateString
            console.log(this[type][name])
        },

        //获取项目详情
        handleChange(e) {
            console.log(e)
            this.getProjectInfo(e)
            if(this.pageType !== 'look'){
              this.getIsProject(e)
            }
        },
        //判断该项目是否可添加次业务
        async getIsProject(e) {
            const [err, res] = await getCostReduction({ projectId: e })
            if (res.data.length > 0 && this.id != res.data[0].id && res.data[0].auditStatus != 'ABOLISH') {
                this.isSubmit = false
                this.$message.warning('成本还原与总结在该项目已存在，不可再次添加')
            } else {
                this.isSubmit = true
            }
        },

        getProjectInfo(id) {
            getProjectInfo({ projectId: id }).then((res) => {
                this.$set(this.form, 'contractEndDate', res.data.contractEndDate)
                this.$set(this.form, 'contractStartDate', res.data.contractStartDate)
                this.$set(this.form, 'structureTypeName', res.data.structureTypeName)
            })
        },

        async checkCostReductionReq() {
            const [err, res] = await checkCostReduction({ id: this.id })
            if (!err) {
                if (res.data.constructionPracticesServiceList) {
                    res.data.constructionPracticesServiceList.forEach((item) => {
                        this.key3++
                        item.key = this.key3
                    })
                } else {
                    res.data.constructionPracticesServiceList = []
                }
                if (res.data.indicatorAnaysisServiceList) {
                    res.data.indicatorAnaysisServiceList.forEach((item) => {
                        this.key2++
                        item.key = this.key2
                    })
                } else {
                    res.data.indicatorAnaysisServiceList = []
                }
                if (res.data.costReductionServiceList) {
                    res.data.costReductionServiceList.forEach((item) => {
                        if (item.children) {
                            item.children.forEach((i) => {
                                i.key = i.id
                                i.isChildren = true
                                delete i.children
                            })
                        } else {
                            item.children = []
                        }

                        item.key = item.id
                    })
                } else {
                    res.data.costReductionServiceList = []
                }

                this.form = res.data
                this.handleChange(this.form.projectId)
                this.getCombined()

                this.$refs.table2.refresh(true)
                this.$refs.table3.refresh(true)
            }
        },

        validateForm() {
            let flag = false
            this.$refs.ruleForm.validate((valid) => {
                flag = valid
                if(!valid) {
                  this.$message.warning("请填写完所有必填项信息")
                }
            })
            return flag
        },
        async delCostReduction(params) {
            const [err, res] = await delCostReduction(params)
            if (!err) {
                this.$message.success('删除成功')
                this.handleClose()
            }
        },
        // 处理增、删、改操作
        async handleSave(status) {
            this.setProcessConfig = null;
            console.log(this.form)
            if (this.loading[status]) return
            if (status != 'DELETE') {
                if (!this.validateForm()) return
                if (isAttachment(this, status, this.form.fileInfoVOList)) return
            }

            let params = Object.assign({}, this.$clone(this.form), { auditStatus: status })
            params.costReductionServiceList.pop()
            const { pageType } = this.$route.query
            const fn = pageType === 'edit' ? editCostReduction : addCostReduction
            const map = {
                DELETE: delCostReduction,
                DRAFT: fn,
                SUBMITTED: fn,
                REJECTED: fn
            }

            if (status == 'DELETE') {
                let that = this
                this.$confirm({
                    title: '温馨提示',
                    content: '确定是否删除数据？',
                    okText: '确认',
                    okType: 'danger',
                    cancelText: '取消',
                    onOk: () => {
                        return that.delCostReduction({id:params.id})
                    }
                })
              this.loading[status] = false
            } else {
                this.loading[status] = true
                this.submitApprovalConfirm(status =='SUBMITTED'?this.processConfig:6, async (flag)=>{
                  if(!flag) {
                    this.loading[status] = false
                    return
                  }
                const [err, res] = await map[status](params)
                if (!err) {
                    if (status === 'REJECTED' || status === 'DRAFT') {
                        this.$message.success('保存成功')
                    } else {
                        this.$message.success('提交成功')
                    }
                if(status =='SUBMITTED') {
                    //提交时，返回id
                        this.businessId = res.data.id;
                        this.setProcessConfig = this.processConfig;
                        return
                    }else{
                    this.handleClose()
                 }
                }
                  this.loading[status] = false
                })
            }


        },
        handleClose() {
            if (this.isAudit) {
                window.close()
            } else {
              this.$router.back()
                // this.$multiTab.close(this.$route.fullpath)
            }
        }
    }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
.updateCostReduction-table{
    .ant-input-number-disabled{
        background-color: #f5f5f5!important;
        border: #f5f5f5;
    }
    .ant-input[disabled] {
        background-color: #f5f5f5!important;
        border: #f5f5f5;
}
}
.tool-btns {
    display: flex;
    justify-content: flex-end;
    @{deep} .ant-btn + .ant-btn {
        margin-left: 12px;
    }
}
.flex {
    display: flex;
    flex-wrap: nowrap;
    align-items: center;
    height: 40px;
}
.title {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    text-align: left;
    font-weight: bold;
    margin-bottom: 24px;
}
.inputSty {
    border-color: #e4ac0b;
    background-color: #fff9e8;
    margin: -5px 0;
    width: 100%;
}
// /deep/ .ant-table-row-cell-break-word {
//     display: flex;
// }
</style>
